package example3;

import org.junit.Test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 加速文件操作
 */
public class BufferedInputOutputTest {
    @Test
    public void writeread() {
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;

        try {
            FileInputStream fileInputStream = new FileInputStream("1.jpg");
            FileOutputStream fileOutputStream = new FileOutputStream("2.jpg");

            bufferedInputStream = new BufferedInputStream(fileInputStream);
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

            byte bytes[] = new byte[100];
            int num = 0;

            //buffered方法的read方法是非阻塞式的
            while ((num = bufferedInputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, num);
                 //最好清空缓冲区
                bufferedOutputStream.flush();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            //只将装饰流关闭，其包装的节点流会被装饰流关闭
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}







